<template>
  <div class="courses-management">
    <div class="toolbar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索课程..."
        class="search-input"
        clearable
        @clear="handleSearch"
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <el-table
      :data="courseList"
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="cover" label="封面" width="120">
        <template #default="{ row }">
          <el-image
            :src="row.cover"
            :preview-src-list="[row.cover]"
            fit="cover"
            class="course-cover"
          >
            <template #error>
              <div class="image-placeholder">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="课程名称" />
      <el-table-column prop="teacher" label="教师" />
      <el-table-column prop="price" label="价格">
        <template #default="{ row }">
          ¥{{ row.price.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="{ row }">
          <el-button-group>
            <el-button type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button 
              type="success" 
              v-if="row.status === 'DRAFT'"
              @click="handlePublish(row)"
            >发布</el-button>
            <el-button 
              type="warning" 
              v-if="row.status === 'PUBLISHED'"
              @click="handleUnpublish(row)"
            >下架</el-button>
            <el-button type="danger" @click="handleDelete(row)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加课程' : '编辑课程'"
      width="400px"
    >
      <el-form
        ref="courseFormRef"
        :model="courseForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="课程名称">
          <el-input v-model="courseForm.title" disabled />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number 
            v-model="courseForm.price" 
            :precision="2" 
            :step="0.01" 
            :min="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="saveLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { Search, Picture } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

export default {
  name: 'CourseManagementView',
  components: {
    Search,
    Picture
  },
  setup() {
    const loading = ref(false)
    const searchQuery = ref('')
    const currentPage = ref(1)
    const pageSize = ref(5)
    const total = ref(0)
    const dialogVisible = ref(false)
    const dialogType = ref('edit')
    const courseFormRef = ref(null)
    const courseList = ref([])
    
    const teacherList = ref([
      { id: 1, name: 'John Doe' },
      { id: 2, name: 'Jane Smith' }
    ])
    
    const courseForm = reactive({
      courseId: '',
      title: '',
      price: 0
    })
    
    const rules = {
      price: [
        { required: true, message: '请输入价格', trigger: 'blur' }
      ]
    }
    
    const getStatusType = (status) => {
      const types = {
        'PUBLISHED': 'success',
        'DRAFT': 'info',
        'UNPUBLISHED': 'warning'
      }
      return types[status] || 'info'
    }
    
    const getStatusText = (status) => {
      const texts = {
        'PUBLISHED': '已发布',
        'DRAFT': '未发布',
        'UNPUBLISHED': '已下架'
      }
      return texts[status] || status
    }
    
    const handleSearch = () => {
      currentPage.value = 1 // 重置页码到第一页
      fetchCourses()
    }
    
    const handleEdit = (row) => {
      Object.assign(courseForm, {
        courseId: row.id,
        title: row.title,
        price: row.price
      })
      dialogType.value = 'edit'
      dialogVisible.value = true
    }
    
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要删除课程 "${row.title}" 吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const response = await request({
            url: '/courseService/courseController/delCourseForBack',
            method: 'delete',
            params: {
              courseId: row.id
            }
          })
          
          if (response.code === 200) {
            ElMessage.success('删除成功')
            fetchCourses() // 刷新列表
          } else {
            ElMessage.error(response.message || '删除失败')
          }
        } catch (error) {
          
          ElMessage.error('删除失败')
        }
      }).catch(() => {})
    }
    
    const handlePublish = async (row) => {
      try {
        const response = await request({
          url: '/courseService/courseController/updateCourseStatus',
          method: 'post',
          params: {
            courseId: row.id,
            status: 1
          }
        })
        
        if (response.code === 200) {
          ElMessage.success(`课程 "${row.title}" 已发布`)
          fetchCourses() // 刷新列表
        } else {
          ElMessage.error(response.message || '发布失败')
        }
      } catch (error) {
        ElMessage.error('发布失败')
      }
    }
    
    const handleUnpublish = async (row) => {
      try {
        const response = await request({
          url: '/courseService/courseController/updateCourseStatus',
          method: 'post',
          params: {
            courseId: row.id,
            status: 0
          }
        })
        
        if (response.code === 200) {
          ElMessage.success(`课程 "${row.title}" 已下架`)
          fetchCourses() // 刷新列表
        } else {
          ElMessage.error(response.message || '下架失败')
        }
      } catch (error) {
        ElMessage.error('下架失败')
      }
    }
    
    const handleCoverSuccess = (res, file) => {
      courseForm.cover = URL.createObjectURL(file.raw)
    }
    
    const beforeCoverUpload = (file) => {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        ElMessage.error('封面必须是图片文件!')
      }
      if (!isLt2M) {
        ElMessage.error('封面大小不能超过 2MB!')
      }

      return isImage && isLt2M
    }
    
    const saveLoading = ref(false)
    
    const handleSubmit = async () => {
      if (!courseFormRef.value) return
      
      try {
        await courseFormRef.value.validate()
        saveLoading.value = true
        
        const response = await request({
          url: '/courseService/courseController/updateCoursePrice',
          method: 'post',
          data: {
            courseId: courseForm.courseId,
            price: courseForm.price
          }
        })
        
        if (response.code === 200) {
          ElMessage.success('更新成功')
          dialogVisible.value = false
          fetchCourses() // 刷新列表
        } else {
          ElMessage.error(response.message || '更新失败')
        }
      } catch (error) {
        ElMessage.error('更新失败')
      } finally {
        saveLoading.value = false
      }
    }
    
    const fetchCourses = async () => {
      try {
        loading.value = true
        const response = await request({
          url: '/courseService/courseController/selectAllCoursesForBack',
          method: 'get',
          params: {
            currentPage: currentPage.value,
            pageSize: pageSize.value,
            courseName: searchQuery.value
          }
        })
        
        if (response.code === 200) {
          courseList.value = response.data.records.map(course => ({
            id: course.courseId,
            title: course.courseName,
            teacher: course.teacherName,
            price: course.price,
            status: course.status === 1 ? 'PUBLISHED' : 'DRAFT',
            cover: course.courseImg
          }))
          total.value = response.data.total
        } else {
          ElMessage.error('获取课程列表失败')
        }
      } catch (error) {
        ElMessage.error('获取课程列表失败')
      } finally {
        loading.value = false
      }
    }
    
    const handleSizeChange = (val) => {
      pageSize.value = val
      fetchCourses()
    }
    
    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchCourses()
    }
    
    onMounted(() => {
      fetchCourses()
    })
    
    return {
      loading,
      searchQuery,
      currentPage,
      pageSize,
      total,
      courseList,
      teacherList,
      dialogVisible,
      dialogType,
      courseForm,
      courseFormRef,
      rules,
      getStatusType,
      getStatusText,
      handleSearch,
      handleEdit,
      handleDelete,
      handlePublish,
      handleUnpublish,
      handleCoverSuccess,
      beforeCoverUpload,
      handleSubmit,
      handleSizeChange,
      handleCurrentChange,
      saveLoading
    }
  }
}
</script>

<style scoped>
.courses-management {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.course-cover {
  width: 80px;
  height: 60px;
  border-radius: 4px;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f7fa;
  color: #909399;
}

.cover-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.cover-uploader:hover {
  border-color: #409eff;
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.cover {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

:deep(.el-button-group) {
  .el-button {
    margin-left: 0;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style> 